import { useCallback, useEffect, useState } from 'react';

import { toast } from 'sonner';
import { getNodeForm, useRefresh, useService } from '@flowgram.ai/free-layout-editor';
import { useClientContext } from '@flowgram.ai/free-layout-editor';

import { CustomService } from '@/services';
import { cn } from '@/lib/utils';
import { useFlowContext } from '@/context/flow-context';

import { Button } from '../ui/button';
import { ToolContainer, ToolSection } from './styles';
import { Save } from './save';
import { Load } from './load';
import { FlowName } from './flowname';
import { RichAiChatBox } from '../chat';

export const FileTools = () => {
  const customService = useService(CustomService);
  const flowContext = useFlowContext();
  const clientContext = useClientContext();
  const [isChatBoxVisible, setIsChatBoxVisible] = useState(false);
  const { playground } = useClientContext();
  const refresh = useRefresh();
  const flow = useFlowContext();

  /**
   * Validate all node and Save
   */
  const onSave = useCallback(async () => {
    const allForms = clientContext.document.getAllNodes().map((node) => getNodeForm(node));
    await Promise.all(allForms.map(async (form) => form?.validate()));
    console.log('flowName1', flowContext.name);
    const flowName = flowContext.name || '';
    console.log('save data', flowName);
    if (flowName === '') {
      console.log('flowName', flowName);
      toast('请输入工作流名称');
      return false;
    }

    const saveData = {
      id: flowContext.id || 0,
      name: flowName,
      data: clientContext.document.toJSON(),
      format: 'flowgram',
    };
    try {
      console.log('saveData', saveData);
      const result = await customService.saveFlow(JSON.stringify(saveData));
      flowContext.setFlow({
        ...flowContext,
        id: result.id,
      });
      console.log('>>>>> result: ', result);
      return true;
    } catch (error) {
      console.log('>>>>> error: ', error);
      return false;
    }
  }, [flowContext, clientContext]);

  const onPlay = useCallback(async () => {
    const flowId = flowContext.id || 0;
    if (flowId === 0) {
      toast('请先保存工作流');
      return null;
    }
    try {
      const result = await customService.runFlow(flowId);
      console.log('>>>>> result: ', result);
      return result;
    } catch (error) {
      console.log('>>>>> error: ', error);
      return null;
    }
  }, [flowContext]);

  const runFlow = async () => {
    // 先保存
    const saveSuccess = await onSave();

    if (!saveSuccess) {
      return; // 保存失败，不再继续
    }

    // 保存成功后运行
    const runResult = await onPlay();

    if (runResult) {
      // 保存运行结果并显示对话框
      setIsChatBoxVisible(true);
    }
  };

  useEffect(() => {
    const disposable = playground.config.onReadonlyOrDisabledChange(() => refresh());
    return () => disposable.dispose();
  }, [playground]);

  return (
    <ToolContainer className="demo-free-layout-tools">
      <ToolSection>
        <FlowName disabled={playground.config.readonly} />
        <Save disabled={playground.config.readonly} />
        <Load />
        <Button className={cn('h-8 w-14 rounded-md md:text-xs border')} onClick={runFlow}>
          运行
        </Button>
      </ToolSection>
      <RichAiChatBox
        flowId={flow.id ?? 0}
        open={isChatBoxVisible}
        onOpenChange={() => setIsChatBoxVisible(false)}
      />
    </ToolContainer>
  );
};
